#include "checksum_16.h"

uint16_t MakeChecksum16(uint8_t *inData, size_t length)
{
    uint32_t sum = 0;

    while (length >= 2U) {
        sum += (uint32_t)inData[0];
        sum += ((uint32_t)inData[1] << 8);
        inData += 2;
        length -= 2;
        sum = (sum & 0xFFFFU) + (sum >> 16);
    }

    if (length == 1U) {
        sum += (uint32_t)inData[0];
        sum = (sum & 0xFFFFU) + (sum >> 16);
    }

    sum = (~sum) & 0xFFFFU;
    sum = (sum + 1U) & 0xFFFFU;

    return (uint16_t)sum;
}

